<template>
  <div>
    <div ref="main" style="height:calc(100vh - 85px);width: 100%;overflow-y: hidden">
      <el-form
        v-show="!drawer &&!showSetting"
        :inline="true"
        style="position: absolute;top: 100px;z-index: 5000;left: 13px"
      >
        <el-form-item>
          <all-product-series-cascade @change="productChange"/>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="status"
            style="width: 100px;"
            :placeholder="$t('status')"
            @change="statusChange"
          >
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-show="netModel !=='local'">
          <all-province-city-cascade
            v-if="isInit"
            :status="status"
            :product-id="productId"
            :province-id="provinceId"
            :city-id="cityId"
            :series-id="seriesId"
            @change="provinceCityChange"
            @province-init="provinceInit"
          />
        </el-form-item>
        <el-form-item v-if="netModel !=='local'">
          <el-switch
            v-model="gather"
            :active-text="$t('gather')"
            active-value="1"
            inactive-value="0"
            @change="listAllDevice"
          />
        </el-form-item>
        <el-form-item v-if="!zooMax">
          <el-button type="warning" icon="el-icon-full-screen" @click="requestFullScreen"/>
        </el-form-item>
        <el-form-item v-else>
          <el-button type="warning" icon="el-icon-crop" @click="exitFullscreen"/>
        </el-form-item>
      </el-form>
      <div
        ref="map"
        style="height:calc(100vh);width: 100%"
      />
    </div>

    <el-dialog
      :visible.sync="showSetting"
      :title="device.deviceName"
      width="1200px"
      top="15px"
    >
      <device-setting
        :device-core="device.deviceCore"
        class="uni-scroll"
        style="height: 600px"
      />
    </el-dialog>

    <el-drawer
      size="70%"
      :visible.sync="drawer"
      direction="rtl"
    >
      <div class="uni-scroll" style="height: calc(100vh - 100px)">
        <sensor-camera-list :device="device"/>
      </div>
    </el-drawer>

  </div>
</template>

<script>
import { exitFullscreen, formatDate, formatSensorType, listDeviceStatus, requestFullScreen } from '@/util/common'
import { listAllDevice } from '@/api/iot/iotDeviceApi'
import AllProductSeriesCascade from '@/components/AllProductSeriesCascade'
import DeviceSetting from '@/components/DeviceSetting'
import SensorCameraList from '@/components/SensorCameraList'
import AllProvinceCityCascade from '@/components/AllProvinceCityCascade'
import { listSensorWith } from '@/api/iot/iotDeviceSensorApi'
import {
  getMapGather,
  getNetModel,
  getSearchDeviceStatus,
  getShowHidden,
  setMapGather,
  setSearchDeviceStatus
} from '@/util/storage'
import {
  addMarketClickListener,
  clearAllMarket,
  hideInfoWindow,
  makeInfoWindow,
  makeMap,
  makeMarkerCluster,
  makeMarket,
  markerClusterAddMarker
} from '@/util/mapTool'

let map = null
let markerCluster = null
let infoWindow = null
export default {
  name: 'PointMap',
  components: {
    SensorCameraList,
    DeviceSetting,
    AllProductSeriesCascade,
    AllProvinceCityCascade
  },
  data() {
    return {
      drawer: false,
      showSetting: false,
      status: getSearchDeviceStatus(),
      provinceId: null,
      cityId: null,
      statusList: [],
      map: null,
      device: {},
      productId: null,
      seriesId: null,
      isInit: false,
      gather: getMapGather(),
      zooMax: false,
      netModel: getNetModel(),
      baseURL: window.VUE_APP_BASE_API,
      dataIndex: 0,
      showHidden: getShowHidden()
    }
  },
  mounted() {
    this.isInit = true
    this.statusList = listDeviceStatus(this)
    map = makeMap(this.$refs.map, this.lat, this.lng)
    markerCluster = makeMarkerCluster(map)
    window.mapDeviceSensor = this.mapDeviceSensor
    window.mapDeviceMore = this.mapDeviceMore
    window.mapDeviceSetting = this.mapDeviceSetting
  },
  methods: {
    gatherChange() {
      this.listDevice()
      setMapGather(this.gather)
    },
    requestFullScreen() {
      requestFullScreen(this.$refs.main)
      this.zooMax = true
    },
    exitFullscreen() {
      exitFullscreen()
      this.zooMax = false
    },
    formatSensorType(type) {
      return formatSensorType(this, type)
    },
    provinceInit() {
      this.listAllDevice()
    },
    provinceCityChange(item) {
      this.provinceId = item.provinceId
      this.cityId = item.cityId
      this.listAllDevice()
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    mapDeviceMore(deviceCore) {
      map.ztn.markerList.forEach(marker => {
        const device = marker.ztn.device
        if (device.deviceCore === deviceCore) {
          this.deviceMore(device)
          return
        }
      })
    },
    mapDeviceSetting(deviceCore) {
      map.ztn.markerList.forEach(marker => {
        const device = marker.ztn.device
        if (device.deviceCore === deviceCore) {
          this.deviceSetting(device)
          return
        }
      })
    },
    mapDeviceSensor(deviceCore) {
      map.ztn.markerList.forEach(marker => {
        const device = marker.ztn.device
        if (device.deviceCore === deviceCore) {
          this.deviceSensor(device)
          return
        }
      })
    },
    deviceSensor(item) {
      this.deviceClick(item)
      this.drawer = true
    },
    deviceMore(item) {
      this.$router.push({
        path: '/device/manage/' + item.deviceCore,
        query: {
          deviceCore: item.deviceCore,
          deviceName: item.deviceName
        }
      })
    },
    deviceSetting(item) {
      this.deviceClick(item)
      this.showSetting = true
    },
    statusChange() {
      this.listAllDevice()
      setSearchDeviceStatus(this.status)
    },
    productChange(val) {
      this.productId = val.productId
      this.seriesId = val.seriesId
      this.listAllDevice()
    },
    listSensorWith(device) {
      const that = this
      listSensorWith({
        deviceCore: device.deviceCore,
        withExplain: true,
        withParam: true,
        withSetting: false
      }).then(res => {
        const { code, data } = res
        const sensorList = []
        if (code === '200') {
          for (const item of data) {
            if (item.hidden) {
              continue
            }
            if (!item.explainList) {
              item.explainList = []
            }
            if (!item.paramList) {
              item.paramList = []
            }
            if (item.explainList.length > 0 || item.paramList.length > 0) {
              sensorList.push(item)
            }
          }
        }
        that.showMapInfo(device, sensorList)
      })
    },
    showMapInfo(device, sensorList) {
      let content = `<div style="width: 200px">
                      <div>${device.deviceName}</div>`

      sensorList.forEach(sensor => {
        if (this.showHidden !== '1' && sensor.hidden) {
          return
        }
        content = content + `<div style="margin: 13px 0;font-size: 13px;color: #e7cc69;">
                                <span style="margin-right: 5px">${sensor.sensorName}</span>
                                <span>[${this.formatSensorType(sensor.type)}${this.$t('port')}:${sensor.port}]</span>
                              </div>`
        sensor.explainList.forEach(explain => {
          if (this.showHidden !== '1' && explain.hidden) {
            return
          }
          content = content + `<div style="height: 20px;width: 100%">
                                    <span style="color: #99a9bf;width: 100px;font-size: 13px">${explain.name}<span style="color: #606266;font-size: 13px;float: right">${explain.value}${explain.unit}</span></span>
                               </div>`
        })
      })
      content = content + `<div style="width: 100%;height: 20px;">
                        <div style="float: right;margin:0 2px">
                          <span class="el-icon-menu " style="font-size: 15px" onclick="mapDeviceMore('${device.deviceCore}')" />
                        </div>
                        <div style="float: right;margin:0 2px">
                          <span class="el-icon-setting" style="font-size: 15px" onclick="mapDeviceSetting('${device.deviceCore}')" />
                        </div>
                        <div style="float: right;margin:0 2px">
                          <span class="el-icon-s-platform" style="font-size: 15px" onclick="mapDeviceSensor('${device.deviceCore}')" />
                        </div>
                      </div>
                    </div>`
      infoWindow = makeInfoWindow(map, device.lat, device.lng, content)
    },
    deviceClick(item) {
      this.device = item
      hideInfoWindow(map, infoWindow)
      this.listSensorWith(item)
    },
    listAllDevice() {
      clearAllMarket(map)
      const req = {
        productId: this.productId,
        seriesId: this.seriesId,
        status: this.status,
        provinceId: this.provinceId,
        cityId: this.cityId,
        fieldList: ['deviceCore', 'lat', 'lng', 'deviceName', 'iconUrl']
      }
      listAllDevice(req).then(res => {
        const { data, code } = res
        if (code === '200') {
          this.pointIndex = 0
          this.makeMarkerList(data)
        }
      })
    },
    makeMarkerList(data) {
      // for (let i = 0; i < 20; i++) {
      //   const marker = this.makeMarker(data[i])
      //   markerClusterAddMarker(map, markerCluster, marker)
      // }
      const that = this
      setTimeout(() => {
        const dataLength = data.length
        for (let i = 0; i < 20; i++) {
          if (that.pointIndex >= dataLength) {
            return
          }
          const marker = that.makeMarker(data[that.pointIndex])
          if (that.gather === '1' && markerCluster) {
            markerClusterAddMarker(map, markerCluster, marker)
          }
          that.pointIndex = that.pointIndex + i
        }
        that.makeMarkerList(data)
      }, 0)
    },
    makeMarker(device) {
      const marker = makeMarket(map, device.lat, device.lng)
      marker.ztn.device = device
      const that = this
      addMarketClickListener(map, marker, (param) => {
        that.deviceClick(param.marker.ztn.device)
      })
      return marker
    }
  }
}
</script>

